package com.jspgou.cms.dao.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;
import com.jspgou.common.hibernate3.Finder;
import com.jspgou.common.hibernate3.HibernateBaseDao;
import com.jspgou.common.page.Pagination;
import com.jspgou.cms.dao.MessageDao;
import com.jspgou.cms.entity.Message;

@Repository
public class MessageDaoImpl extends HibernateBaseDao<Message, Integer> implements MessageDao {
	
	public Pagination getPage(Long sendMemberId,
			Long receiverMemberId, String title, Date sendBeginTime,
			Date sendEndTime, Boolean status, Integer box, Boolean cacheable,
			int pageNo, int pageSize) {
		String hql = " select msg from Message msg where 1=1 ";
		Finder finder = Finder.create(hql);
		if(sendMemberId != null&&receiverMemberId != null){
			finder.append(" and (msg.msgSendUser.id=:sendMemberId or msg.msgReceiverUser.id=:receiverMemberId)").setParam(
					"sendMemberId", sendMemberId).setParam("receiverMemberId", receiverMemberId);
		}else{
			if (sendMemberId != null) {
				finder.append(" and msg.msgSendUser.id=:sendMemberId").setParam(
						"sendMemberId", sendMemberId);
			}
			if (receiverMemberId != null) {
				finder.append(" and msg.msgReceiverUser.id=:receiverMemberId")
						.setParam("receiverMemberId", receiverMemberId);
			}
		}
		
		if (StringUtils.isNotBlank(title)) {
			finder.append(" and msg.msgTitle like:title").setParam("title",
					"%" + title + "%");
		}
		if (sendBeginTime != null) {
			finder.append(" and msg.sendTime >=:sendBeginTime").setParam(
					"sendBeginTime", sendBeginTime);
		}
		if (sendEndTime != null) {
			finder.append(" and msg.sendTime <=:sendEndTime").setParam(
					"sendEndTime", sendEndTime);
		}
		if (status != null) {
			if (status) {
				finder.append(" and msg.msgStatus =true");
			} else {
				finder.append(" and msg.msgStatus =false");
			}
		}
		if (box != null) {
			finder.append(" and msg.msgBox =:box").setParam("box", box);
		}
		finder.append(" order by msg.id desc");
		return find(finder, pageNo, pageSize);
	}

	public Message findById(Integer id) {
		return super.get(id);
	}

	public Message save(Message bean) {
		getSession().save(bean);
		return bean;
	}
	
	public Message update(Message bean){
		getSession().update(bean);
		return bean;
	}

	public Message deleteById(Integer id) {
		Message entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	public Message[] deleteByIds(Integer[] ids) {
		Message[] messages = new Message[ids.length];
		for (int i = 0; i < ids.length; i++) {
			messages[i] = get(ids[i]);
			deleteById(ids[i]);
		}
		return messages;
	}

	@Override
	protected Class<Message> getEntityClass() {
		return Message.class;
	}

}